import LcWebRequest, {TimeUnit} from 'lc-web-request';
import configs from 'WE/configs';
import {L} from 'lc-simple-js-common';
import * as AxiosLogger from 'axios-logger';
import {globalService} from 'M/Services';

const tranLanguage = {
  en: 'en-US',
  zh: 'zh-CN',
};

/**
 * 缓存的URLs
 * @type {{"/enums/userTypes": {expires: number, timeUnit: string}, "/enums/userStatus": {expires: number, timeUnit: string}}}
 */
const cacheUrls = {
  '/users/me': {
    timeUnit: TimeUnit.DAYS,
    expires: 1,
  },
};

export class Request {
  constructor(baseURL) {
    this.request = LcWebRequest({
      baseURL,
      cacheUrls,
      responseInterceptor: response =>
        __DEV__ ? AxiosLogger.requestLogger(response) : response,
      requestInterceptor: config => {
        config.headers = {
          ...config.headers,
          ...globalService.getDeviceInfo(),
          'X-DEVICE-INFO': navigator.userAgent,
          'Accept-Language': tranLanguage.zh || navigator.language,
        };
        return __DEV__ ? AxiosLogger.requestLogger(config) : config;
      },
    });
  }

  postBody({body, path, ...options}) {
    return execute(this.request, {
      data: body,
      url: L.addFirstSlash(path),
      ...options,
      method: 'post',
    });
  }

  post({path, ...options}) {
    return execute(this.request, {
      url: L.addFirstSlash(path),
      ...options,
      method: 'post',
    });
  }

  get({path, ...options}) {
    return execute(this.request, {
      url: L.addFirstSlash(path),
      ...options,
      method: 'get',
    });
  }

  put({path, ...options}) {
    return execute(this.request, {
      url: L.addFirstSlash(path),
      ...options,
      method: 'put',
    });
  }

  delete({path, ...options}) {
    return execute(this.request, {
      url: L.addFirstSlash(path),
      ...options,
      method: 'delete',
    });
  }
}

const execute = (request, config) =>
  new Promise((resolve, reject) => {
    request
      .request(config)
      .then(({data: {data}}) => resolve(data))
      .catch(e => {
        if (__DEV__) {
          AxiosLogger.errorLogger(e);
        }
        reject(e);
      });
  });

export default {
  smsRequest: new Request(L.addLashSlash(configs.SmsPlatformBasePath)),
  lpRequest: new Request(L.addLashSlash(configs.LongPayBasePath)),
};
